//
//  GSServerManager.m
//  AgileNYC
//
//  Created by German Sidorenko on 09.05.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSServerManager.h"
#import "AFNetworking.h"
#import "GSAccessToken.h"
#import "SGSUtils.h"
//#import "OAMutableURLRequest.h"


@interface SGSServerManager () <UIWebViewDelegate>

@property (strong, nonatomic) AFHTTPRequestOperationManager * requestOperationManager;
//@property (weak, nonatomic) UIWebView * loginDialogWebView;
@property (strong, nonatomic) UIActivityIndicatorView * spinner;

@property (copy, nonatomic) NSString * currentAuthHost;
@property (strong, nonatomic) GSAccessToken* currentToken;

@property (weak, nonatomic) NSString * currentTokenKey;
@property (weak, nonatomic) NSString * currentExpiredKey;
@property (weak, nonatomic) NSString * currentUserIDKey;
@property (weak, nonatomic) NSString * currentErrorKey;

//@property (copy, nonatomic) GSCompletionBlock loginCompletionBlock;

@property (weak, nonatomic) GSUser * currentUser;

//@property(nonatomic, retain) OAConsumer *consumer;
//@property(nonatomic, retain) OAToken *requestToken;

@end


@implementation SGSServerManager

#pragma mark - Conctructors

+(SGSServerManager*) sharedManager {
    static SGSServerManager * manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SGSServerManager alloc] init];
        //manager.requestOperationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        
    });
    
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSURL * serverURL = [NSURL URLWithString:agileURL];
        self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:serverURL];
//#if !DEBUG
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        securityPolicy.allowInvalidCertificates = YES;
        self.requestOperationManager.securityPolicy = securityPolicy;
//#endif
        self.currentToken = [[GSAccessToken alloc] init];
    }
    
    return self;
}

-(void) initRequestManagerWithURL:(NSString*) serverURL {
    NSURL * URL = [NSURL URLWithString:serverURL];
    self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:URL];
}

- (void)dealloc
{
  //  self.loginDialogWebView.delegate = nil;
}

#pragma mark - - Requests to Server (AFHTTPRequestOperationManager) - -

#pragma mark - Events List

-(void) getEventsList:(NSString*) currentUserToken
               offcet:(NSInteger) offset
                count:(NSInteger) count
            onSuccess:(void(^)(NSArray * arrayWithDictionaryOfEvents)) success
            onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
    static int currentPageNumber = 1;

#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             //currentUserToken ,@"usertoken",
                             (currentUserToken) ? currentUserToken : @"", @"usertoken",
                             @(offset),@"offset",
                             //@(-1),@"offset",
                             @(count),@"Limit",
                             nil];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", eventsGroup,getEventsListMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"getEventsList: %@", responseObject);
                                  //NSLog(@"%@", operation.request.URL);
                                  
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  
                                  if ([tempStr isKindOfClass:[NSNull class]]) {
                                      if (success) {
                                          success(nil);
                                      }
                                  } else {
                                      
                                      NSError * e;
                                      
                                      NSArray * result =
                                      [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                      options: NSJSONReadingMutableContainers
                                      error: &e];
                                      
                                      if (success) {
                                          success(result);
                                      }
                                  }

                                  currentPageNumber++;
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (failure) {
                                     failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) checkInOnEvent:(NSString*) currentUserToken
               eventID:(NSNumber*) eventID
                  flag:(BOOL) flag
             onSuccess:(void(^)()) success
             onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {

#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken               ,@"usertoken",
                             eventID                        ,@"eventID",
                             (flag) ? @"true" : @"false"    ,@"isCheckIn",
                             nil];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", eventsGroup,checkInOnEventMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"%@", responseObject);
                                  
                                  if (success) {
                                      success();
                                  }
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) rateEvent:(NSString*) currentUserToken
               eventID:(NSNumber*) eventID
                rating:(NSNumber*) rating
             onSuccess:(void(^)(NSDictionary * eventInfo)) success
             onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken   ,@"usertoken",
                             eventID            ,@"eventId",
                             rating             ,@"RatingValue",
                             nil];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", eventsGroup,rateEventMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"%@", responseObject);
                                  
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  
                                  if ([tempStr isKindOfClass:[NSNull class]]) {
                                      if (success) {
                                          success(nil);
                                      }
                                  } else {
                                      NSError * e;
                                      NSDictionary * result =
                                      [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                      options: NSJSONReadingMutableContainers
                                                                        error: &e];
                                      
                                      if (success) {
                                          success(result);
                                      }
                                  }
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

#pragma mark - User operations

-(void) checkEmail: (NSString*) eMail
         onSuccess:(void(^)(BOOL result)) success
         onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             eMail ,@"Email",
                             nil];
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,checkUserEmailMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                   
                                   //NSLog(@"%@", responseObject);
                                   
                                   NSString * tempStr = [responseObject valueForKey:resultKey];

                                   if ([tempStr isKindOfClass:[NSNull class]]) {
                                       if (success) {
                                           success(NO);
                                       }
                                   } else {
                                       if (success) {
                                           success([tempStr boolValue]);
                                       }
                                   }
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];

}


-(BOOL) loginUser: (NSString*) eMail
         password: (NSString*) password
       socialType: (GSLoginType) socialType
      deviceToken: (NSString*) deviceToken
        onSuccess:(void(^)(NSDictionary * userInfo, NSString * errorString)) success
        onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {

    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             eMail ,@"Email",
                             //(password) ? password : @"", @"Password",
                             password, @"Password",
                             [NSNumber numberWithInteger:socialType], @"SocialType",
                             [NSNumber numberWithInt:myDeviceOSType], @"DeviceOs",
                             [NSNumber numberWithInteger:myDeviceMobileType], @"MobileWorkingSystem",
                             deviceToken, @"DeviceId",
                             (YES) ? @"true" : @"false", @"IsCheck",  //Means that we only check user, not create
                             nil];
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self.requestOperationManager POST:[NSString stringWithFormat:@"%@/%@", usersGroup,loginUserMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                   
                                   //NSLog(@"%@", responseObject);
                                   
                                   NSString * tempStr = [responseObject valueForKey:resultKey];
                                   NSString * errorStr = [responseObject valueForKey:errorKey];
                                   	
                                   if ([tempStr isKindOfClass:[NSNull class]]) {
                                       if (success) {
                                           success(nil, errorStr);
                                       }
                                   } else {
                                       NSError * e;
                                       NSDictionary * result =
                                       [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                       options: NSJSONReadingMutableContainers
                                                                         error: &e];

                                       if (success) {
                                           success(result, nil);
                                       }
                                   }
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif
    
    return YES;
}


-(BOOL) createUser: (NSString*) eMail
          password: (NSString*) password
        socialType: (GSLoginType) socialType
       deviceToken: (NSString*) deviceToken
         onSuccess:(void(^)(NSDictionary * userInfo)) success
         onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {

    
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             eMail ,@"Email",
                             (password) ? password : @"" , @"Password",
                             [NSNumber numberWithInteger:socialType], @"SocialType",
                             [NSNumber numberWithInt:myDeviceOSType], @"DeviceOs",
                             [NSNumber numberWithInteger:myDeviceMobileType], @"MobileWorkingSystem",
                             (NO) ? @"true" : @"false", @"IsCheck",                                     //Means that we create the user
                             (deviceToken) ? deviceToken : @"", @"DeviceId",                            //Check for nil
                             nil];
    
    //NSLog(@"%@", params);
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self.requestOperationManager POST:[NSString stringWithFormat:@"%@/%@", usersGroup,loginUserMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
     
                                   //NSLog(@"--- %@", responseObject);
                                   //NSLog(@"--- %@", operation.request.URL);
                                   
                                   NSString * tempStr = [responseObject valueForKey:resultKey];
                                   NSString * errorStr = [responseObject valueForKey:errorKey];
                                   
                                   if ((errorStr) && ([errorStr length]>0)) {
                                       if (failure) {
                                           NSError * error = [NSError errorWithDomain:errorStr code:0 userInfo:nil];
                                           failure(error, 0);
                                       }
                                   } else if ([tempStr isKindOfClass:[NSNull class]]) {
                                       if (success) {
                                           success(nil);
                                       }
                                   } else {
                                       NSError * e;
                                       NSDictionary * result =
                                       [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                       options: NSJSONReadingMutableContainers
                                                                         error: &e];
                                       
                                       if (success) {
                                           success(result);
                                       }
                                   }
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif
    return YES;
}

-(void) getUserInfo:(NSString*) currentUserToken
          onSuccess:(void(^)(NSDictionary * dictionaryOfUser)) success
          onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             nil];

    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,getUserMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"%@", responseObject);
                                  
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  
                                  if ([tempStr isKindOfClass:[NSNull class]]) {
                                      if (success) {
                                          success(nil);
                                      }
                                  } else {
                                      
                                      NSError * e;
                                      NSDictionary * result =
                                      [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                      options: NSJSONReadingMutableContainers
                                                                        error: &e];
                                      
                                      if (success) {
                                          success(result);
                                      }
                                  }

                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) postUserInfo:(NSString*) currentUserToken
          dictOfUser:(NSDictionary*) dictOfUser
           onSuccess:(void(^)(void)) success
           onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    //self.requestOperationManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //self.requestOperationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];


    [self.requestOperationManager POST:[NSString stringWithFormat:@"%@/%@", usersGroup,putUserMethod]
                           parameters:dictOfUser
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"%@", responseObject);

                                  NSNumber * val = [responseObject objectForKey:resultKey];
                                  //NSString * errorStr = [responseObject valueForKey:errorKey];
                                  
                                  if ((val) && (![val isKindOfClass:[NSNull class]])) {
                                      BOOL res = [val boolValue];
                                      
                                      if (res) {
                                          if (success) {
                                              success();
                                          }
                                      } else {
                                          if (failure) {
                                              NSError * error = [NSError errorWithDomain:@"Unable to save data" code:7 userInfo:nil];
                                              failure(error, 0);
                                          }
                                      }
                                  } else {
                                      NSError * error = [NSError errorWithDomain:@"Unknown answer received" code:5 userInfo:nil];
                                      failure(error, 0);
                                  }
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) postUserImage:(NSString*) currentUserToken
          imageOfUser:(NSData*) imageOfUser
            onSuccess:(void(^)(NSString * newUrl)) success
            onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    self.requestOperationManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    UIImage * jpgImage = [UIImage imageWithData:imageOfUser];
    NSData * jpgData = UIImageJPEGRepresentation(jpgImage, 0.5);

    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[NSData dataWithData:jpgData]];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@/%@/%@", agileURL, usersGroup,putPhotoMethod,currentUserToken];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"binary/octet-stream" forHTTPHeaderField: @"Content-Type"];
    [request setHTTPBody:body];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //NSLog(@"%@", data);
        if ([data length] >0 && connectionError == nil)
        {
            NSError * e;
            NSDictionary * result =
            [NSJSONSerialization JSONObjectWithData: data
                                            options: NSJSONReadingMutableContainers
                                              error: &e];
            
            NSString * tempStr = [result valueForKey:resultKey];
            NSString * errorStr = [result valueForKey:errorKey];
                
            if ((errorStr) && ([errorStr length]>0)) {
                if (failure) {
                    NSError * error = [NSError errorWithDomain:errorStr code:0 userInfo:nil];
                    failure(error, 0);
                }
            } else if ([tempStr isKindOfClass:[NSNull class]]) {
                if (success) {
                    success(nil);
                }
            } else {
                if (success) {
                    success(tempStr);
                }
            }
        }
        else if ([data length] == 0 && connectionError == nil)
        {
            if (success) {
                success(nil);
            }
        }
        else if (connectionError != nil){
            if (failure) {
                failure(connectionError, 0);
            }

        }
    }];

#endif
    
}

-(void) getUserImage:(NSString*) currentUserToken
              userID:(NSNumber*) userID
           onSuccess:(void(^)(NSData * userImage)) success
           onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
#ifndef LOCAL_DATA
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             userID,@"code",
                             nil];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@", photoGroup]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                   
                                   //NSLog(@"%@", responseObject);
                                   
                                   if ([responseObject isKindOfClass:[NSData class]]) {
                                       if (success) {
                                           success(responseObject);
                                       }
                                   } else {
                                       if (failure) {
                                             NSError * error = [NSError errorWithDomain:@"No photo" code:2 userInfo:nil];
                                             failure(error, 0);
                                       }
                                   }
                                   
                                   //BOOL res = [[responseObject objectForKey:resultKey] boolValue];
                                   
                                   /*if (res) {
                                       if (success) {
                                           success();
                                       }
                                   } else {
                                       if (failure) {
                                           //  NSError * error = [NSError errorWithDomain:@"Unable to save data" code:230783 userInfo:nil];
                                           //  failure(error, 0);
                                       }
                                   }*/
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   
                                   //NSLog(@"%@",operation.request.URL);
                                   
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif
}


-(void) deleteUserImage:(NSString*) currentUserToken
              onSuccess:(void(^)(void)) success
              onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
#ifndef LOCAL_DATA
    
    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             nil];

    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,deletePhotoMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                   
                                   //NSLog(@"%@", responseObject);
                                   
                                   BOOL res = [[responseObject objectForKey:resultKey] boolValue];
                                   
                                   if (res) {
                                       if (success) {
                                           success();
                                       }
                                   } else {
                                       if (failure) {
                                             NSError * error = [NSError errorWithDomain:@"Unable to delete image" code:3 userInfo:nil];
                                             failure(error, 0);
                                       }
                                   }
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif
}


#pragma mark - Connection to another user

-(void) sendConnection:(NSString*) currentUserToken
              toUserID:(NSNumber*) anotherUserID
             onSuccess:(void(^)(void)) success
             onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             anotherUserID,@"code",
                             nil];


    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,connectMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                   
                                   //NSLog(@"%@", responseObject);
                                   
                                   NSString * tempStr = [responseObject valueForKey:resultKey];
                                   
                                   if (!([tempStr isKindOfClass:[NSNull class]]) && ([tempStr isEqualToString:unknownUserAnswer])) {
                                       if (failure) {
                                           NSError * err = [NSError errorWithDomain:@"The Connect ID is not valid" code:1 userInfo:nil];
                                           failure(err,0);
                                       }
                                       
                                   } else {
                                       if (success) {
                                           success();
                                       }
                                   }
                                   
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif

}

-(void) sendConnectionReply:(NSString*) currentUserToken
                   toUserID:(NSNumber*) anotherUserID
                      reply:(BOOL) reply
                  onSuccess:(void(^)(void)) success
                  onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken, @"usertoken",
                             anotherUserID, @"code",
                             (reply) ? @"True" : @"False", @"agree",
                             nil];
    
    //NSLog(@"REPLY PARAMS: %@", params);

    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,connectionReplyMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                               
                                   if (success) {
                                       success();
                                   }
                               
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif

}

-(void) checkConnection:(NSString*) currentUserToken
              onSuccess:(void(^)(NSDictionary * arrayWithDictionaryOfRequestors)) success
              onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {

#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             nil];

    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,connectionCheckMethod]
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                   
                                   //NSLog(@"checkConnection: %@", responseObject);
                                   //NSLog(@"--- %@", operation.request.URL);
                                 
                                   /*NSArray * result = [responseObject objectForKey:resultKey];

                                   if (success) {
                                       success(result);
                                   }*/
                                   
                                   NSString * tempStr = [responseObject valueForKey:resultKey];
                                   
                                   if ([tempStr isKindOfClass:[NSNull class]]) {
                                       if (success) {
                                           success(nil);
                                       }
                                   } else {
                                       
                                       NSError * e;
                                       NSArray * result =
                                       [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                       options: NSJSONReadingMutableContainers
                                                                         error: &e];
                                       
                                       if ((result) && ([result count] > 0)) {
                                           
                                           NSDictionary * resultDict = [result objectAtIndex:0];
                                           
                                           if (success) {
                                               success(resultDict);
                                           }
                                       } else {
                                           if (success) {
                                               success(nil);
                                           }
                                       }
                                   }
                               }
                               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   
                                   GSLog(GSLogError, @"URL: %@", operation.request.URL);

                                   if (failure) {
                                       failure(error, operation.response.statusCode);
                                   }
                               }];
#endif
    
}

-(void) deleteContact:(NSString*) currentUserToken
               userID:(NSNumber*) userID
              onSuccess:(void(^)(void)) success
              onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
    
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             userID, @"code",
                             nil];
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,deleteContactMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"%@", responseObject);
                                  
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  
                                  if (!([tempStr isKindOfClass:[NSNull class]]) && ([tempStr isEqualToString:unknownUserAnswer])) {
                                      if (failure) {
                                          NSError * err = [NSError errorWithDomain:@"Wrong user id" code:1 userInfo:nil];
                                          failure(err,0);
                                      }
                                      
                                  } else {
                                      if (success) {
                                          success();
                                      }
                                  }
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  
                                  GSLog(GSLogError, @"URL: %@", operation.request.URL);
                                  
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) getContactsList:(NSString*) currentUserToken
                 offcet:(NSInteger) offset
                  count:(NSInteger) count
              onSuccess:(void(^)(NSArray * arrayWithDictionaryOfContacts)) success
              onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
#ifndef LOCAL_DATA
    __strong NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken,@"usertoken",
                             @(offset),@"offset",
                             @(count),@"Limit",
                             nil];
    
    //NSLog(@"%@", params);
    
    [self.requestOperationManager GET:[NSString stringWithFormat:@"%@/%@", usersGroup,getContactsMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  
                                  //NSLog(@"getContactsList: %@", responseObject);
                                  //NSLog(@"getContactsList URL: %@", operation.request.URL);
                              
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  
                                  if ([tempStr isKindOfClass:[NSNull class]]) {
                                      if (success) {
                                          success(nil);
                                      }
                                  } else {
                                      
                                      NSError * e;
                                      
                                      NSArray * result =
                                      [NSJSONSerialization JSONObjectWithData: [tempStr dataUsingEncoding:NSUTF8StringEncoding]
                                                                      options: NSJSONReadingMutableContainers
                                                                        error: &e];
                                      
                                      //NSLog(@"%@", result);
                                      
                                      if (success) {
                                          success(result);
                                      }
                                  }

                              
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  
                                  //NSLog(@"getContactsList URL: %@", operation.request.URL);

                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

-(void) saveNotesForContact:(NSString*) currentUserToken
                  toUserID:(NSNumber*) anotherUserID
                     notes:(NSString*) notes
                 onSuccess:(void(^)(void)) success
                 onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure {
#ifndef LOCAL_DATA
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUserToken, @"UserToken",
                             anotherUserID, @"Code",
                             notes, @"NoteText",
                             nil];

    self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.requestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self.requestOperationManager POST:[NSString stringWithFormat:@"%@/%@", usersGroup,saveNotesForContactMethod]
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                  
                                  //NSLog(@"saveNotesForContact: %@", responseObject);
                                  
                                  NSString * tempStr = [responseObject valueForKey:resultKey];
                                  NSString * errorStr = [responseObject valueForKey:errorKey];
                                  
                                  if ((errorStr) && ([errorStr length]>0))  {
                                      if (failure) {
                                          NSError * error = [NSError errorWithDomain:errorStr code:0 userInfo:nil];
                                          failure(error, 0);
                                      }
                                  } else if ([tempStr isKindOfClass:[NSNull class]]) {
                                      if (success) {
                                          success();
                                      }
                                  } else {
                                      if (success) {
                                          success();
                                      }
                                  }
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (failure) {
                                      failure(error, operation.response.statusCode);
                                  }
                              }];
#endif
    
}

#pragma mark - Dialogs

/*
-(void) showExternalLoginDialogWithURL:(NSString*) urlString caption:(NSString*) caption {
    UIViewController * mainVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController * vc = [[UIViewController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    CGRect rect = mainVC.view.bounds;
    rect.origin = CGPointZero;
    
    UIWebView * webView = [[UIWebView alloc] initWithFrame:rect];
    self.loginDialogWebView = webView;
    
    webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    webView.delegate = self;
    
    [vc.view addSubview:webView];
    vc.navigationItem.title = caption;
    
    UIBarButtonItem * cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onCancelLoginButtonClick:)];
    UIBarButtonItem * activityButton = [[UIBarButtonItem alloc] initWithCustomView:self.spinner];
    [vc.navigationItem setRightBarButtonItem:cancelButton];
    [vc.navigationItem setLeftBarButtonItem:activityButton];
    
    [mainVC presentViewController:nav animated:YES completion:nil];
    
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url];
    
    [webView loadRequest:urlRequest];
}*/
/*
-(void) hideExternalLoginDialog {
    UIViewController * mainVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    self.loginDialogWebView.delegate = nil;
    
    [self stopSpinner];
    
    self.spinner = nil;
    
    [mainVC dismissViewControllerAnimated:YES completion:nil];
}*/

#pragma mark - NSMutableURLRequest
/**
-(void) makeRequestToURL:(NSString*) urlString
                    type:(NSString*) requestType
               onSuccess:(void(^)(NSDictionary * dict)) success
               onFailure:(void(^)(NSError * error, NSInteger statusCode)) failure
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:requestType];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if ([data length] >0 && connectionError == nil)
        {
            NSError * e;
            NSDictionary * result =
            [NSJSONSerialization JSONObjectWithData: data
                                            options: NSJSONReadingMutableContainers
                                              error: &e];
            if (success) {
                success(result);
            }
        }
        else if ([data length] == 0 && connectionError == nil)
        {
            if (success) {
                success(nil);
            }
        }
        else if (connectionError != nil){
            if (failure) {
                failure(connectionError,0);
            }
        }
    }];
}
*/

#pragma mark - Actions
/*
-(void) onCancelLoginButtonClick:(id) sender {
    [self hideExternalLoginDialog];
}
*/
#pragma mark - UIWebViewDelegate
/*
// Отлавливаем URL с токенами
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    GSLog(GSLogInfo, @"%@", [request URL]);
    GSLog(GSLogInfo, @"Current HOST: %@", [[request URL] host]);
    GSLog(GSLogInfo, @"Auth host: %@", self.currentAuthHost);
    
    NSError * error = nil;
    BOOL isSuccess = [[[request URL] host] isEqualToString:self.currentAuthHost];
    
    if (isSuccess) {
        
        NSString * query = [[request URL] query];
        
        if (query==nil) {
            query = [[request URL] absoluteString] ;
        }
        
        NSArray * array = [query componentsSeparatedByString:@"#"];
        
        if ([array count]>1) {
            query = [array lastObject];
        }
        
        NSArray * pairs = [query componentsSeparatedByString:@"&"];
        
        for (NSString * pair in pairs) {
            NSArray * keyAndValues = [pair componentsSeparatedByString:@"="];
            
            if ([keyAndValues count] >1) {
                
                NSString * key = [keyAndValues firstObject];
                
                if ([key isEqualToString:self.currentTokenKey]) {
                    self.currentToken.token = [[keyAndValues lastObject] copy];
                } else if ([key isEqualToString:self.currentExpiredKey]) {
                    NSTimeInterval interval = [[keyAndValues lastObject] doubleValue];
                    self.currentToken.expiration = [NSDate dateWithTimeIntervalSinceNow:interval];
                } else if ([key isEqualToString:self.currentUserIDKey]) {
                    self.currentToken.userID = [keyAndValues lastObject];
                } else if ([key isEqualToString:self.currentErrorKey]) {
                    error = [[NSError alloc] initWithDomain:[keyAndValues lastObject] code:0 userInfo:nil];
                    isSuccess = NO;
                }
            }
        }
        
        [self hideExternalLoginDialog];
        
        //return NO;
    }
    
    if (self.loginCompletionBlock) {
        self.loginCompletionBlock(isSuccess,error,0);
    }
    
    webView.delegate = self;
    
    return !isSuccess;
    
    //return YES;
}*/


- (void)webViewDidStartLoad:(UIWebView *)webView {
    //[self startSpinnerOnView:webView];
    
    [self startSpinnerOnView:webView];
    
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)webViewDidFinishLoad {
    [self stopSpinner];
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self stopSpinner];
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}


#pragma mark - Spinner

-(void) startSpinnerOnView:(UIView*) view {
    /*self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.spinner.center = CGPointMake(160, 240);

    if (view==nil) {
       view = [UIApplication sharedApplication].keyWindow.rootViewController.view;
    }
    
    [view addSubview:self.spinner];
    
    [self.spinner startAnimating];*/
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    //UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:ai];
    
    //view.
    
    //UINavigationController * nav = (UINavigationController*) view;
    //nav.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:ai];
    //[ai startAnimating];
    //[ai release];
    
    //[self.spinner startAnimating];
}

-(void) stopSpinner {
    /*[self.spinner stopAnimating];
    self.spinner = nil;*/
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
    //[self.spinner stopAnimating];
}

@end
